//
//  DeviceManager.m
//  KaiXinDa
//
//  Created by stonesMonkey on 2018/11/13.
//  Copyright © 2018年 stonesMonkey. All rights reserved.
//

/**
 // 读身份证操作执行结束后，该方法被调用，返回结果。可调用processIdCardInfo对information拆分成数组
 
 *  读证代理
 *
 *  @param returnCode  返回状态 0 成功
 *  @param information 二代身份证信息
 *  @param NEphoto       身份证人像面
 *  @param IWphoto      国徽面照片。
 *  @param error       错误信息
 
 // 二代身份证信息以|分割并如下顺序：如 姓名|性别|民族|年|月|日|地址|公民身份证号|签发机关|有效期|头像照片。NEphoto身份证人像面, IWphoto国徽面照片。
 - (void)iMateDelegateIDReadMessage:(NSInteger)returnCode
 information:(NSData *)information
 nationalEmblemPhoto:(NSData*)NEphoto
 identityWitness: (NSData*)IWphoto
 error:(NSString *)error;
 
 
 

 */

#import "KXDSafetyBox.h"
#import <ExternalAccessory/ExternalAccessory.h>
#import <UIKit/UIKit.h>

#import "RequestDataTool.h"
#import "RNTimer.h"
#import "VPODataModel.h"
#import "KaiXinDaConstant.h"
#import "RequestDataTool.h"
#define kDefalutTime 30
#define kScanIdCarDefalutTime 60



// 每次最低执行秒数，防止重点,当执行结束，定时器直接消失
#define kTouchMaxSecond 10
static KXDSafetyBox *shareManager;

@interface KXDSafetyBox()<EAAccessoryDelegate,NSStreamDelegate>

@property (nonatomic, strong) EAAccessory *selectedAccessory;
@property (nonatomic, strong) NSArray *supportedProtocolsStrings;


// 会话
@property (nonatomic, strong) EASession *session;
@property (nonatomic, strong) NSMutableData *writeData;
@property (nonatomic, strong) NSMutableData *readData;

@property (nonatomic) EAAccessory *accessory;
@property (nonatomic) NSString *protocolString;

@property (nonatomic, copy)NSString *dataStr;

@property (nonatomic, assign)SendType sendType;

@property (nonatomic, strong)RNTimer *timer;

@property (nonatomic, strong)NSMutableData *receverData;

/// 操作消耗的时间
@property (nonatomic, assign)NSInteger actionTime;

@property (nonatomic, assign)ResetCardType slot;

@property (nonatomic, assign)ReadFingerprint print;

@property (nonatomic, strong)VPODataModel *dataModel;

@property (nonatomic, copy)NSString *param1;

@property (nonatomic, assign)BOOL isScan;
/// 刷卡超时时间
//@property (nonatomic, assign)NSInteger swipeTimeOut;
//// 扫描超时时间
//@property (nonatomic, assign)NSInteger scanTimeOut;
//// 指纹特征超时时间
//@property (nonatomic, assign)NSInteger readFingerPrintFeatureOutTime;
//// 指纹模板超时
//@property (nonatomic, assign)NSInteger readFingerPrintTemplateTimeOut;
//// 刷磁条卡超时
//@property (nonatomic, assign)NSInteger readMagneticCardTimeOut;
///// 身份证刷卡超时时间
//@property (nonatomic, assign)NSInteger readMessageTimeOut;
//// 身份证超时
//@property (nonatomic, assign)NSInteger exitIDCardTimeOut;
@property (nonatomic, assign)ReadIDCardMessgae cardMessageType;

@property (nonatomic, assign)ReadIDCardOperation operation;

@property (nonatomic, assign)NSInteger eventId;

@property (nonatomic, copy)NSString *aid;

@property (nonatomic, assign)BOOL isCheckIC;
@property (nonatomic, assign)NSInteger timeOut;
@property (nonatomic, assign)BOOL isWaitCard;

// accessoryList ValueChange
@property (nonatomic, copy) KXDBlock accessoryListChange;
// 提示用户请不要频繁点击触发block 或者正在执行
@property (nonatomic, copy)KXDBlock reClickBlock;

@property (nonatomic, assign)FunctionAction myAction;

@end

@implementation KXDSafetyBox {
    
    BOOL  _isConnect;
}

+ (instancetype)shareInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        shareManager = [[self alloc] init];
        // 有设备连接触发的时间
        [[NSNotificationCenter defaultCenter] addObserver:shareManager selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
        // 有设备断开链接触发的事件
        [[NSNotificationCenter defaultCenter] addObserver:shareManager selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
        [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
    
    });
    return shareManager;
}


#pragma mark - 客户要求的方法
// 二维码扫描
- (void)scanQRCode:(NSInteger)timeout {
    
    self.myAction = ScanQRCodeActon;
    [self scanHeadStaring];
    self.timeOut = timeout;
    if (self.timeOut < 70) {
        
        self.timeOut = 70;
    }
    [self startTime];
    
}
// 读取指纹特征值
- (void)readFingerPrintFeature:(NSInteger)timeout {
    
    self.myAction = readFingerPrintFeatureAction;
    self.timeOut = timeout;
    [kKXDSafetyBox fingerprintModulReadType:ReadFingerprintCharacteristics];
    if (self.timeOut < kDefalutTime) {
        
        self.timeOut = kDefalutTime;
    }
    [self startTime];
}

// 读取指纹模板
- (void)readFingerPrintTemplate:(NSInteger)timeout {
    self.myAction = readFingerPrintTemplateAction;
    self.timeOut = timeout;
    [kKXDSafetyBox fingerprintModulReadType:ReadFingerprintModel];
    if (self.timeOut < kDefalutTime) {
        
        self.timeOut = kDefalutTime;
    }
    [self startTime];
}
// 磁条刷卡
- (void)readMagneticCard:(NSInteger)timeOut {
    
    self.myAction = readMagneticCardAction;
    self.timeOut = timeOut;
    
    [kKXDSafetyBox icResetCard:ResetCardSwipeCardType tag:OpenMagneticCardType timeout:timeOut];
    if (self.timeOut < kDefalutTime) {
        
        self.timeOut = kDefalutTime;
    }
    [self startTime];
}

// 读身份证信息
-(void)readIDCardInformation:(NSInteger)timeout {
    
    self.myAction = readIDCardInformationAction;
    self.timeOut = timeout;
    self.cardMessageType = ReadIDCardMessgaeInfomation;
    if (self.timeOut < kScanIdCarDefalutTime) {
        
        self.timeOut = kScanIdCarDefalutTime;
    }
    [kKXDSafetyBox idCardOpen];
    [self startTime];
}


// 读身份证图片
-(void)readIDCardPicture:(NSInteger)operation timeout:(NSInteger)timeout {
    
    self.myAction = readIDCardPictureActon;
    self.timeOut = timeout;
    if (self.timeOut < kScanIdCarDefalutTime) {
        
        self.timeOut = kScanIdCarDefalutTime;
    }
    self.operation = operation;
    [kKXDSafetyBox idCardOpen];
    [self startTime];
    self.cardMessageType = ReadIDCardMessgaePhoto;
}

// IC卡信息
-(void)readICCardInformation:(NSInteger)slot aid:(NSString*)aid timeout:(NSInteger)timeOut {
    
    self.myAction = readICCardInformationAction;
    self.aid = aid;
    self.timeOut = timeOut;
    self.isCheckIC = YES;
    if (self.timeOut < kDefalutTime) {
        self.timeOut = kDefalutTime;
    }
    
    if (slot > 7) {
        
        slot = 7;
    }
    self.slot = slot;
    // 需要先复位
    [self autoCheckCard:slot];
    [self startTime];
    
}

// 3.7 等待刷卡(接触式IC卡、非接触式IC卡、磁卡)事件
- (void)waitSwipeCardEvent:(Byte)eventMask timeout:(NSInteger)timeout {
     self.myAction = waitSwipeCardEventAction;
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
        self.timeOut = timeout;
        if (self.timeOut < kDefalutTime) {
            
            self.timeOut = kDefalutTime;
        }
        self.isWaitCard = YES;
        self.isCheckIC = NO;
        NSInteger slot = eventMask;
        if (slot > 7) {
            slot = 7;
        }
        self.slot = slot;
        self.eventId = eventMask;
        [self autoCheckCard:slot];
        [self startTime];
    });
    

  
}
// 退出身份证
- (void)exitIDCard {
    
    self.myAction = exitIDCardAction;
    if (self.timeOut < kScanIdCarDefalutTime) {
        
        self.timeOut = kScanIdCarDefalutTime;
    }
    
    [self idCardExit];
    [self startTime];
    
}


// 读取IC插入，并对IC卡进行复位请求，结果通过delegate响应
// slot＝0为用户芯片插槽，slot=1为射频卡，slot>=4为SAM卡座,
// tag将被传递给iMateDelegateICResetCard，可做为后续执行操作的标示
// timeout为最长等待时间(秒)
- (void)icResetCard:(ResetCardType)slot tag:(SendType)tag timeout:(NSInteger)timeout {
    
    self.dataModel = nil;
    self.sendType = tag;
    self.slot = slot;
    
    [self autoCheckCard:slot];
}

// 等待事件，包括磁卡刷卡、Pboc IC插入、放置射频卡。timeout是最长等待时间(秒)
// eventMask的bit来标识等待事件：
//      0x01    等待刷卡事件
//      0x02    等待插卡事件
//      0x04    等待射频事件
//      0xFF    等待所有事件
// 等待的结果通过delegate响应
- (void)waitEvent:(Byte)eventMask timeout:(NSInteger)timeout {
    
    //    [self autoCheckCard:6];
}


- (void)getCurrentDeviceLevel {
    
    
}


#pragma mark - 检测是否正在执行
- (void)startTime {
    
    
    if (self.timer != nil) {
        
        if (self.reClickBlock) {
            self.reClickBlock();
        }
    }
    self.receverData = [NSMutableData new];
    //
    self.actionTime = 0;
    //    self.swipeTimeOut = 120;
    self.timer = [RNTimer repeatingTimerWithTimeInterval:1 block:^{
    
        // 扫码超时
        self.actionTime = self.actionTime + 1;
        if ( self.myAction == ScanQRCodeActon && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n扫码超时,设备不响应";
            if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
                [self.delegate iMateDelegateNoResponse:error];
                        }
            
        }
        
        // 读取指纹特征值超时
        if (self.myAction == readFingerPrintFeatureAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n读取指纹特征值超时,设备不响应";
             if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
            [self.delegate iMateDelegateNoResponse:error];
              
             }
        }
        
        // 读取指纹模板超时
        if (self.myAction == readFingerPrintTemplateAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n读取指纹模板超时,设备不响应";
             if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
            [self.delegate iMateDelegateNoResponse:error];
             }
        }
        
        // 刷卡超时
        if (self.myAction == readMagneticCardAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n刷卡命令读取超时,设备不响应";
             if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
            [self.delegate iMateDelegateNoResponse:error];
             }
        }
        
        // 读取身份证信息超时
        if (self.myAction == readIDCardInformationAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n读取身份证信息超时,设备不响应";
            if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
                [self.delegate iMateDelegateNoResponse:error];
            }
        }
        
        // 扫描身份证件超时
        if (self.myAction == readIDCardPictureActon && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n扫描身份证件超时,设备不响应";
            if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
                [self.delegate iMateDelegateNoResponse:error];
            }

        }
        
        // 等待刷卡
        if (self.myAction == waitSwipeCardEventAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n等待刷卡事件超时,设备不响应";
            if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
                [self.delegate iMateDelegateNoResponse:error];
            }
        }
        
        // 读IC卡超时
        if (self.myAction == readICCardInformationAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            self.isCheckIC = NO;
            NSString *error = @"-2\n读IC卡超时,设备不响应";
            if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
                [self.delegate iMateDelegateNoResponse:error];
            }
        }
        
        // 退卡超时
        if (self.myAction == exitIDCardAction && self.actionTime > self.timeOut) {
            
            [self endTime];
            NSString *error = @"-2\n退卡超时,设备不响应";
            if ([self.delegate respondsToSelector:@selector(iMateDelegateNoResponse:)]) {
                [self.delegate iMateDelegateNoResponse:error];
            }
        }
        
        
        
    }];
    
}

- (void)swipeTimeOutAction {
    
    if (self.sendType == AutoCheckCardType) {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateSwipeCard:track2:track3:error:)]) {
            
            [self.delegate iMateDelegateSwipeCard:-1  track2:nil track3:nil error:@"请求超时！"];
            self.sendType = NotType;
            [self endTime];
        }
    }
}

- (void)endTime {
    
    self.sendType = NotType;
    [self.timer invalidate];
    
    self.timer = nil;
}

#pragma mark - 操作方法
///1.1打开磁条卡
-(void)openMagneticCard {
    
    NSData *data = [RequestDataTool openMagneticCard];
    self.sendType = OpenMagneticCardType;
    [self writeData:data];
}

///1.2检查刷卡
-(void)checkCreditCard {
    
    NSData *data = [RequestDataTool checkCreditCard:self.timeOut];
    self.sendType = CheckCreditCardType;
    [self writeData:data];
}

///1.3取消刷卡
-(void)cancelCreditCard {
    
    NSData *data = [RequestDataTool cancelCreditCard];
    self.sendType = CancelCreditCardType;
    [self startTime];
    [self writeData:data];
}

///2.1自动检卡
-(void)autoCheckCard:(ResetCardType)slot {
    
    if (self.slot == ResetCardSwipeCardType) {
        
        [self openMagneticCard];
        return;
    }
    
    if (slot == 3) {
        
        NSData *data = [RequestDataTool autoCheckCard:slot];
        self.sendType = AutoCheckCardType;
        [self writeData:data];
        return;
    }
    
    if (slot == 2 || slot == 4 || slot == 7 ) {
        
        NSData *data = [RequestDataTool autoCheckCard:slot];
        self.sendType = AutoCheckCardType;
        [self writeData:data];
    }
    
    //    NSData *data = [RequestDataTool autoCheckCard:slot];
    //    self.sendType = AutoCheckCardType;
    //     [self startTime];
    //    [self writeData:data];
    
}

///2.2开启PBOC流程
-(void)startPBOCProcess:(ResetCardType)slot {
   
    
    [self endTime];
    NSData *data = [RequestDataTool startPBOCProcess:slot];
    self.sendType = StartPBOCProcessType;
    [self startTime];
    [self writeData:data];
    
    
}

///2.3获取55域（IC卡复位只调用自动检卡)
-(void)obtainDomain55 {
    
    if (self.slot !=ResetCardSwipeCardType &&
        self.slot != ResetCardSlotCardType &&
        self.slot != ResetCardSAMType &&
        self.slot != ResetCardRFCardType &&
        self.slot != ResetCardAutomaticCardType
        ) {
        return;
    }
    NSData *data = [RequestDataTool obtainDomain55:self.slot];
    self.sendType = ObtainDomain55Type;
    [self startTime];
    [self writeData:data];
}

///2.4取消读卡（IC卡复位只调用自动检卡）
-(void)unreadCard {
    
    NSData *data = [RequestDataTool unreadCard];
    self.sendType = UnreadCardType;
    [self startTime];
    [self writeData:data];
}

///3.1 打开扫描头
-(void)scanHeadOpen {
    
    NSData *data = [RequestDataTool scanHeadOpen];
    self.sendType = ScanHeadOpenType;
    [self writeData:data];
}

///3.2 扫描头扫码
-(void)scanHeadStar {
    
    NSData *data = [RequestDataTool scanHeadStar];
    self.sendType = ScanHeadStarType;
    [self writeData:data];
}

///
- (void)scanHeadStaring {
    
    [self scanHeadOpen];
}

///4.1 打开指纹模块
-(void)fingerprintModuleOpen {
    
    NSData *data = [RequestDataTool fingerprintModuleOpen];
    self.sendType = FingerprintModuleOpenType;
    [self writeData:data];
}

///4.2 读取指纹模版
-(void)fingerprintModuleRead {
    
    NSData *data = [RequestDataTool fingerprintModuleRead];
    self.sendType = FingerprintModuleReadType;
    [self writeData:data];
}

-(void)fingerprintModulReadType:(ReadFingerprint)print {
    
    self.print = print;
    [self fingerprintModuleOpen];
    
}

///4.3 读取指纹特征
-(void)fingerprintReadCharacteristics {
    
    NSData *data = [RequestDataTool fingerprintReadCharacteristics];
    self.sendType = FingerprintReadCharacteristicsType;
    [self writeData:data];
}

///4.4 检测手指是否按下
-(void)fingerprintWhetherPress {
    
    NSData *data = [RequestDataTool fingerprintWhetherPress];
    self.sendType = FingerprintWhetherPressType;
    [self startTime];
    [self writeData:data];
}

///5.1  打开二代证
-(void)idCardOpen {
    
    NSData *data = [RequestDataTool idCardOpen];
    self.sendType = IdCardOpenType;
    [self writeData:data];
}

///5.2  扫描身份证
-(void)idCardScan {
    
    NSData *data = [RequestDataTool idCardScan:self.timeOut type:self.cardMessageType];
    self.sendType = IdCardScanType;
    [self writeData:data];
}

///5.3 关闭二代证模块
-(void)idCardClose {
    
    NSData *data = [RequestDataTool idCardClose];
    self.sendType = IdCardCloseType;
    [self startTime];
    [self writeData:data];
}

///5.4 退卡
-(void)idCardExit {
    
    NSData *data = [RequestDataTool idCardExit];
    self.sendType = IdCardExitType;
    [self writeData:data];
}

- (void)getARQC {
    
    NSData *data = [RequestDataTool idCardExit];
    self.sendType = GetARQC;
    self.actionTime = kDefalutTime;
    [self startTime];
    [self writeData:data];
}


#pragma mark Internal
- (void)_accessoryDidConnect:(NSNotification *)notification { // 参照系统写法
    EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    
    if (connectedAccessory.protocolStrings.count == 0) {
        return;
    }
    BOOL isTure = [connectedAccessory.protocolStrings[0] isEqualToString:@"com.issc.datapath"];
    
    if (isTure == YES) {
        
        isTure = [connectedAccessory.name containsString:@"Chatboard"];
        if (isTure == NO) {
            [self openSession];
            return;
        }
    }
    
    if (isTure) {
        
        _isConnect = [self openSession];
        isTure = _isConnect;
    }
    
    if (isTure) {
        
        [self.accessoryList addObject:connectedAccessory];
    }
  

    
    if (self.accessoryListChange) {
        self.accessoryListChange();
    }
   
    if ([self.delegate respondsToSelector:@selector(iMateDelegateConnectStatus:)] && isTure) {
        [self.delegate iMateDelegateConnectStatus:isTure];
    }
}

- (void)_accessoryDidDisconnect:(NSNotification *)notification { // 参照系统写法
    EAAccessory *disconnectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    
    if (_selectedAccessory && [disconnectedAccessory connectionID] == [_selectedAccessory connectionID])  {
        
    }
    
    int disconnectedAccessoryIndex = 0;
    for(EAAccessory *accessory in _accessoryList) {
        if ([disconnectedAccessory connectionID] == [accessory connectionID]) {
            break;
        }
        disconnectedAccessoryIndex++;
    }
    
    if (disconnectedAccessoryIndex < [_accessoryList count]) {
        [_accessoryList removeObjectAtIndex:disconnectedAccessoryIndex];
        
        if (self.accessoryListChange) {
            self.accessoryListChange();
        }
    } else {
//
    }
    
    BOOL isTure = [disconnectedAccessory.protocolStrings[0] isEqualToString:@"com.issc.datapath"];
    if (isTure == YES) {
        
        isTure = [disconnectedAccessory.name containsString:@"Chatboard"];
    }
  
    if ([self.delegate respondsToSelector:@selector(iMateDelegateConnectStatus:)] && isTure) {
        [self.delegate iMateDelegateConnectStatus:NO];
           NSLog(@"disconnect in");
        _isConnect=NO;
        
    }
}



- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidConnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidDisconnectNotification object:nil];
}


- (EAAccessory *)accessory {
    
    if (self.accessoryList.count > 0) {
        
        return self.accessoryList[0];
    }
    return nil;
}

- (NSString *)protocolString {
    
    if (self.accessory) {
        
        if ([self.accessory.protocolStrings count] > 0) {
            
            return [self.accessory.protocolStrings firstObject];
        }
    }
    return nil;
}

#pragma mark - 会话
/// 开启回话
- (BOOL)openSession
{
   
    if (_accessory == nil && self.accessoryList.count > 0) {
        
        _accessory = self.accessoryList[0];
        [_accessory setDelegate:self];
    } else {
        
         [_accessory setDelegate:self];
    }
    
    _session = [[EASession alloc] initWithAccessory:self.accessory forProtocol:self.protocolString];
    
    if (_session)
    {
        [[_session inputStream] setDelegate:self];
        [[_session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [[_session inputStream] open];
        
        [[_session outputStream] setDelegate:self];
        [[_session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [[_session outputStream] open];
    }
    else
    {
//        NSLog(@"creating session failed");
    }
    
    return (_session != nil);
}

/// 结束会话
- (void)closeSession
{
    [[_session inputStream] close];
    [[_session inputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [[_session inputStream] setDelegate:nil];
    [[_session outputStream] close];
    [[_session outputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [[_session outputStream] setDelegate:nil];
    _session = nil;
    _writeData = nil;
    _readData = nil;
}

#pragma mark - 写入 & 读取
// high level write data method
- (void)writeData:(NSData *)data
{
    self.receverData = [NSMutableData new];
    if (_writeData == nil) {
        _writeData = [[NSMutableData alloc] init];
    }
    
    [_writeData appendData:data];
    [self writeDataX];
}

// high level read method
- (NSData *)readData:(NSUInteger)bytesToRead
{
    NSData *data = nil;
    if ([_readData length] >= bytesToRead) {
        NSRange range = NSMakeRange(0, bytesToRead);
        data = [_readData subdataWithRange:range];
        [_readData replaceBytesInRange:range withBytes:NULL length:0];
    }
    return data;
}

- (NSUInteger)readBytesAvailable
{
    return [_readData length];
}

#pragma mark EAAccessoryDelegate
- (void)accessoryDidDisconnect:(EAAccessory *)accessory {
    // do something ...
    NSLog(@"dd");
    _isConnect = NO;
}

#pragma mark NSStreamDelegateEventExtensions
// asynchronous NSStream handleEvent method
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventNone:
//            NSLog(@"%@",@"NSStreamEventNone");
            break;
        case NSStreamEventOpenCompleted:
//            NSLog(@"%@",@"NSStreamEventOpenCompleted");
            break;
        case NSStreamEventHasBytesAvailable:
            [self _readData];
            break;
        case NSStreamEventHasSpaceAvailable:
            [self writeDataX];
            break;
        case NSStreamEventErrorOccurred:
//            NSLog(@"%@",@"NSStreamEventErrorOccurred");
            break;
        case NSStreamEventEndEncountered:
//            NSLog(@"%@",@"NSStreamEventEndEncountered");
            break;
        default:
            break;
    }
}


#pragma mark Internal
// low level write method - write data to the accessory while there is space available and data to write
- (void)writeDataX {
    while (([[_session outputStream] hasSpaceAvailable]) && ([_writeData length] > 0))
    {
        NSInteger bytesWritten = [[_session outputStream] write:[_writeData bytes] maxLength:[_writeData length]];
        if (bytesWritten == -1)
        {
//            NSLog(@"write error");
            break;
        }
        else if (bytesWritten > 0)
        {
            [_writeData replaceBytesInRange:NSMakeRange(0, bytesWritten) withBytes:NULL length:0];
//            NSLog(@"bytesWritten %ld", (long)bytesWritten);
            
        }
    }
}

// low level read method - read data while there is data and space available in the input buffer
- (void)_readData {
#define EAD_INPUT_BUFFER_SIZE 128
    uint8_t buf[EAD_INPUT_BUFFER_SIZE];
    _readData = [[NSMutableData alloc] init];
    while ([[_session inputStream] hasBytesAvailable])
    {
        NSInteger bytesRead = [[_session inputStream] read:buf maxLength:EAD_INPUT_BUFFER_SIZE];
        if (_readData == nil) {
            _readData = [[NSMutableData alloc] init];
        }
        [_readData appendBytes:(void *)buf length:bytesRead];
        //        NSLog(@"read %ld bytes from input stream", (long)bytesRead);
    }
    
    [self readDeviceData:_readData];

}




#pragma mark - getData
- (void)readDeviceData:(NSData *)data {
    
    BOOL isLast = NO;
    [self.receverData appendData:data];
    if (data.length < 2) {
        return;
    }
    NSData *checkData = [data subdataWithRange:NSMakeRange(data.length - 2, 2)];
    NSString *checkDataStr = [ZYFDataConversionTool convertDataToHexStr:checkData];
    if ([checkDataStr isEqualToString:@"1001"]) { // 尾针
        

        isLast = YES;

    }
    
    if (self.sendType == IdCardExitType) {
        
        if (isLast == YES) {
            
            [self IdCardExitSuccess];
        }
        return;
    }
    
    if (self.sendType == FingerprintModuleReadType) {
        
        if (isLast == YES) {
            
            [self FingerprintReadModalSuccess];
        }
        return;
    }
    
    if (self.sendType == FingerprintModuleOpenType) {
        
        if (isLast == YES) {
            
            BOOL isSuccess = [self openPrintModulCarSuccess];
            if (isSuccess) {
                if (self.print == ReadFingerprintCharacteristics) {
                    
                    [self fingerprintReadCharacteristics];
                    return;
                } else {
                    [self fingerprintModuleRead];
                    return;
                }
            }
        }
        return;
    }
    
    if (self.sendType == FingerprintReadCharacteristicsType) {
        
        if (isLast == YES) {
            
            [self FingerprintReadCharacteristicsSuccess];
            
        }
        return;
    }
    
    if (self.sendType == GetARQC) {
        
        if (isLast == YES) {
            
            
        }
        return;
    }
    
    if (self.sendType == StartPBOCProcessType) { // 开启流程成功
        
        if (isLast == YES) {
            
            BOOL isSuccess =  [self startPBOCProcessSuccess];
            if (isSuccess) {
                
               [self obtainDomain55];
            }
        }
        return;
    }
    
    
    if (self.sendType == IdCardScanType) { // 身份证扫码
        
        if (isLast == YES) {
            
            [self scanIDCardSuccess];
        }
        return;
    }
    
    if (self.sendType == IdCardOpenType) {
        
        if (isLast == YES) {
            
            BOOL isSuccess = [self openScanCarSuccess];
            if (isSuccess) {
                [self idCardScan];
            }
            
        }
        return;
    }
    
    if (self.sendType == AutoCheckCardType) {// 自动检卡成功
        
        if (isLast == YES) { // 收到结束针
            
            BOOL isSuccess = [self autoCheckCardTypeSuccess];
            if (isSuccess && (self.slot == ResetCardSlotCardType || self.slot == ResetCardSAMType) && self.isCheckIC == YES) {
                //
//                [self startPBOCProcess:self.slot];
                [self autoCheckCard:6];
            } else if (isSuccess && self.slot == ResetCardSwipeCardType){
                
                [self readMagneticCard:20];
                //                if ([self.delegate respondsToSelector:@selector(iMateDelegateSwipeCard:track2:track3:error:)]) {
                //                    [self.delegate iMateDelegateSwipeCard:-1 track2:nil track3:nil error:@"自动检卡失败"];
                //                }
            }
        }
        return;
    }
    
    if (self.sendType == ScanHeadOpenType) {
        
        if (isLast == YES) { // 收到结束针
            
            BOOL isSuccess = [self openScanHearSuccess];
            if (isSuccess) {
                
                [self scanHeadStar];
            } else {
                
                
            }
            
        }
        return;
    }
    
    if (self.sendType == ScanHeadStarType) {
        
        if (isLast == YES) { // 收到结束针
            
            [self openScanCarStrSuccess];
        }
        return;
    }
    
    if (self.sendType == ObtainDomain55Type) {
        
        if (isLast == YES) { // 收到结束针
            
            [self ObtainDomain55TypeSuccess];
        }
        return;
    }
    
    if (self.sendType == OpenMagneticCardType) {
        
        if (isLast == YES) {
            
            BOOL isSuccess = [self openMagneticCardSuccess];
            if (isSuccess) {
                
                [self checkCreditCard];
            }
        }
        return;
    }
    
    if (self.sendType== CheckCreditCardType) {
        
        if (isLast == YES) {
            
            [self checkCreditCardSuccess];
            
        }
        return;
    }
    
}
#pragma mark - 检查数据是否成功
- (BOOL)checkData:(NSDictionary *)dict {
    
    if ([dict isKindOfClass:[NSDictionary class]] && [[dict allKeys] containsObject:@"resultCode"] && [dict[@"resultCode"] integerValue] == 0) {
        
        return YES;
    }
    
    return NO;
}

- (BOOL)checkDataTwo:(NSDictionary *)dict {
    
    if ([dict isKindOfClass:[NSDictionary class]] && [[dict allKeys] containsObject:@"resultCode"]) {
        
        return YES;
    }
    
    return NO;
}

#pragma mark - 完成动作后触发

- (BOOL)IdCardExitSuccess {
    
    [self endTime];
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
    if ([self checkDataTwo:dict]) {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateIDCardExit:error:)]) {
            
            [self.delegate iMateDelegateIDCardExit:dataModel.resultCode error:dataModel.resultMsg];
        }
        
        return YES;
    } else {
        
    }
    
    
    return YES;
}

// 检查刷卡成功
- (BOOL)checkCreditCardSuccess {
    
    [self endTime];
    if (![self.delegate respondsToSelector:@selector(iMateDelegateSwipeCard:track2:track3:error:)]) {
        
        return NO;
    }
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
    if ([self checkDataTwo:dict]) {
        
        [self.delegate iMateDelegateSwipeCard:dataModel.resultCode track2:dataModel.data.track2 track3:dataModel.data.track3 error:dataModel.resultMsg];
        
        return YES;
    } else {
        
        //        [self.delegate iMateDelegateFingerprintModuleRead:-1 model:dataModel.param1 error:@"设备检查刷卡失败"];
    }
    
    return NO;
}

// 读取指纹模板成功
- (BOOL)FingerprintReadModalSuccess {
    
    [self endTime];
    if (![self.delegate respondsToSelector:@selector(iMateDelegateFingerPrintTemplate:template:error:)]) {
        
        return NO;
    }
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
    if ([self checkDataTwo:dict]) {
        
        [self.delegate iMateDelegateFingerPrintTemplate:dataModel.resultCode template:[dataModel.param1 dataUsingEncoding:NSUTF8StringEncoding] error:dataModel.resultMsg];
        
        return YES;
    } else {
        
        [self.delegate iMateDelegateFingerPrintTemplate:-1 template:nil error:@"数据格式错误"];
    }
    return NO;
}

// 读取指纹特征值
- (BOOL)FingerprintReadCharacteristicsSuccess {
    
    [self endTime];
    if (![self.delegate respondsToSelector:@selector(iMateDelegateFingerPrintFeature:fpData1:fpData2:error:)]) {
        
        return NO;
    }
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
    if ([self checkDataTwo:dict]) {
        
        [self.delegate iMateDelegateFingerPrintFeature:dataModel.resultCode fpData1:[dataModel.param1 dataUsingEncoding:NSUTF8StringEncoding] fpData2:nil error:dataModel.resultMsg];
        
        return YES;
    } else {
        
        [self.delegate iMateDelegateFingerPrintFeature:-1 fpData1:nil fpData2:nil error:@"数据格式错误"];
    }
    return NO;
}

// 打开磁条卡成功
- (BOOL)openMagneticCardSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    
    if ([self checkDataTwo:dict]) {
        
        VPODataModel *model = [VPODataModel modelWithDict:dict];
        if (model.resultCode == 0) {
            
            return YES;
        } else {
            
            
            if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
                
                [self.delegate iMateDelegateModuleStatus:NO];
            }
            [self endTime];
        }
        
        return YES;
    } else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
        
    }
    return NO;
}

/**
 打开扫描头成功
 */
- (BOOL)openScanHearSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    if ([self checkData:dict]) {
        
        
        return YES;
    } else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
        
        return NO;
    }
    
    return NO;
}

/**
 开启55域成功
 */
- (BOOL)ObtainDomain55TypeSuccess {
    
    [self endTime];
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    
    if ([self checkDataTwo:dict]) {
        
        VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
        // 55域
        self.dataModel.param1 = dataModel.param1;
        self.dataModel.fiftyFiveZoon = [ZYFDataConversionTool getFiftyFiveZoon:dataModel.param1];
        self.dataModel.aid = [ZYFDataConversionTool getAid:dataModel.param1];
        self.dataModel.offlineDealMessage = [ZYFDataConversionTool offlineDealMessage:dataModel.param1];
        /**
         IC卡复位信息|卡号|卡序号|等效二磁track2|aid|55域|脱机交易信息
         */
//        NSArray *arr = @[
//                         self.dataModel.resetInformation == nil?@"":self.dataModel.resetInformation,
//                         self.dataModel.data.cardNum==nil?@"":self.dataModel.data.cardNum,
//                         self.dataModel.data.sn==nil?@"":self.dataModel.data.sn,
//                         self.dataModel.data.track2==nil?@"":self.dataModel.data.track2,
//                         self.dataModel.aid==nil?@"":self.dataModel.aid,
//                         self.dataModel.fiftyFiveZoon == nil?@"":self.dataModel.fiftyFiveZoon,
//                         self.dataModel.offlineDealMessage ==nil?@"":self.dataModel.offlineDealMessage,
//                         ];
        
        NSString *tag1 = @"000000100000";
        NSString *tag2 = @"000000100000";
        NSString *tag3 = @"000000000000";
        NSRange range1 = [self.dataModel.fiftyFiveZoon rangeOfString:@"9f78"];
        if (range1.location != NSNotFound) {
            
            NSRange range2 = [self.dataModel.fiftyFiveZoon rangeOfString:@"9f7806"];
            if (range2.location !=NSNotFound && self.dataModel.fiftyFiveZoon.length > range2.location + range2.length + 12) {
                
                tag1 = [self.dataModel.fiftyFiveZoon substringWithRange:NSMakeRange(range2.location + range2.length, 12)];
            }
            
            NSRange range3 = [self.dataModel.fiftyFiveZoon rangeOfString:@"9f7706"];
            if (range3.location !=NSNotFound && self.dataModel.fiftyFiveZoon.length > range3.location + range3.length + 12) {
                
                tag2 = [self.dataModel.fiftyFiveZoon substringWithRange:NSMakeRange(range3.location + range3.length, 12)];
            }
            
            NSRange range4 = [self.dataModel.fiftyFiveZoon rangeOfString:@"9f7906"];
            if (range4.location !=NSNotFound && self.dataModel.fiftyFiveZoon.length > range4.location + range4.length + 12) {
                
                tag3 = [self.dataModel.fiftyFiveZoon substringWithRange:NSMakeRange(range4.location + range4.length, 12)];
            }
        }
        /**
         经过解析，第一个为卡号，第二个为sn，第三个为二磁道，第四个为AID，第五个为55域
         第六个为脱机交易信息
         第七八九个为脱机交易信息三个标签下面的值
         第十个为复位信息
         
         */
        
        NSString *fuweiXinXi = self.param1;
        if (self.myAction == waitSwipeCardEventAction) {
            
            fuweiXinXi = self.param1;
        } else {
            
            fuweiXinXi = self.dataModel.resetInformation;
        }
        NSArray *arr = @[
                         self.dataModel.data.cardNum==nil?@"":self.dataModel.data.cardNum,
                        self.dataModel.data.sn==nil?@"":self.dataModel.data.sn,
                         self.dataModel.data.track2==nil?@"":self.dataModel.data.track2,
                         self.dataModel.aid==nil?@"":self.dataModel.aid,
                         self.dataModel.fiftyFiveZoon == nil?@"":self.dataModel.fiftyFiveZoon,
                         self.dataModel.offlineDealMessage ==nil || self.dataModel.offlineDealMessage.length == 0?@"9F78060000001000009F77060000001000009F7906000000000000":self.dataModel.offlineDealMessage,
                         tag1,
                         tag2,
                         tag3,
                         fuweiXinXi == nil?@"":fuweiXinXi,
                         ];
        NSString * str = [arr componentsJoinedByString:@"|"];
    
        if (self.myAction == waitSwipeCardEventAction) {
            
            if ([self.delegate respondsToSelector:@selector(iMateDelegateWaitEvent:eventId:data:error:)]) {
                
                [self.delegate iMateDelegateWaitEvent:self.dataModel.resultCode eventId:self.slot data:[str dataUsingEncoding:NSUTF8StringEncoding] error:self.dataModel.resultMsg];
            }
            
        } else {
            if ([self.delegate respondsToSelector:@selector(iMateDelegateICCardInfo:information:error:)]) {
                
                [self.delegate iMateDelegateICCardInfo:self.dataModel.resultCode information:str error:self.dataModel.resultMsg];
            }
            
        }
      
       
        
        [self endTime];
        if (self.dataModel.resultCode != 0) {
            
            return NO;
        }
        
        return YES;
    }  else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
    }
    return NO;
}

/**
 扫描成功
 */
- (BOOL)openScanCarStrSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    
    VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
    if ([self checkDataTwo:dict]) {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateScanQRCode:qrCodeData:error:)]) {
            
             [self.delegate iMateDelegateScanQRCode:dataModel.resultCode qrCodeData:dataModel.param1 error:dataModel.resultMsg];
        }
         [self endTime];
        if (dataModel.resultCode !=0) {
            
            return NO;
        }
        
        return YES;
    } else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
        
    }
    return NO;
    
}

/**
 打开模板成功
 */
- (BOOL)openPrintModulCarSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    if ([self checkData:dict]) {
        
        
        return YES;
    } else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
        
        return NO;
    }
    
    return NO;
}

/**
 打开二代证成功
 */
- (BOOL)openScanCarSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    
    if ([self checkData:dict]) {
        
        return YES;
    } else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
    }
    return NO;
}

/**
 开启流程成功
 */
- (BOOL)startPBOCProcessSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    
    if ([self checkDataTwo:dict]) {
        
        VPODataModel *dataModel = [VPODataModel modelWithDict:dict];
        NSString *resetInformation = self.dataModel.param1;
        
        self.dataModel = dataModel;
        self.dataModel.resetInformation = resetInformation;
        
        if (self.dataModel.resultCode != 0 ) {
            
            if (self.slot == 2 || self.slot == 4) {
                
                if ([self.delegate respondsToSelector:@selector(iMateDelegateICCardInfo:information:error:)]) {
                    
                    [self.delegate iMateDelegateICCardInfo:self.dataModel.resultCode information:nil error:self.dataModel.resultMsg];
                }
                [self endTime];
            }
            self.dataModel = nil;
            return NO;
        }
        return YES;
        
    } else {
        
        if (self.slot == 2 || self.slot == 4) {
            
            if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
                
                [self.delegate iMateDelegateModuleStatus:NO];
            }
            [self endTime];
            return NO;
        }
        
        return NO;
    }
    return NO;
}


/**
 扫描二代身份证
 */
- (void)scanIDCardSuccess {
    
    [self endTime];
    if (self.cardMessageType == ReadIDCardMessgaeInfomation) {
        
        if (![self.delegate respondsToSelector:@selector(iMateDelegateIDReadMessage:information:error:)]) {
            
            return;
        }
    }
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    
    if ([self checkDataTwo:dict]) {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateIDReadMessage:information:error:)]) {
            
            if (self.cardMessageType == ReadIDCardMessgaeInfomation) {
                
                [self.delegate iMateDelegateIDReadMessage:[dict[@"resultCode"] intValue] information:[dict[@"data"] dataUsingEncoding:NSUTF8StringEncoding] error:dict[@"resultMsg"]];
                
                [kKXDSafetyBox idCardExit];
            }
        }
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateIDCardPicture:headPhoto:nationalEmblemPhoto:identityWitness:error:)]) {
            
            if (self.cardMessageType == ReadIDCardMessgaePhoto) {
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.02 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                   __block  NSData *data1 = [ZYFDataConversionTool strForData:dict[@"param1"]];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                       __block  NSData *data2 = [ZYFDataConversionTool strForData:dict[@"param2"]];
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            
                           __block NSData *data3 = [ZYFDataConversionTool strForData:dict[@"param3"]];
                            
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                
                                if (self.operation == 1) {
                                    
                                    data2 = nil;
                                    data3 = nil;
                                }
                                if (self.operation == 2) {
                                    
                                    data1 = nil;
                                }
                                
                                [self.delegate iMateDelegateIDCardPicture:[dict[@"resultCode"] intValue]
                                                                headPhoto:data1
                                                      nationalEmblemPhoto:data3
                                                          identityWitness:data2
                                                                    error:dict[@"resultMsg"]];
                                
                                [kKXDSafetyBox idCardExit];
                            });
                        });
                    });
                });
            }
        }
        
    } else {
        
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
    }
    
}
// 自动检卡成功
- (BOOL)autoCheckCardTypeSuccess {
    
    NSDictionary *dict = [ZYFDataConversionTool dataByDict:self.receverData];
    VPODataModel *model = [VPODataModel modelWithDict:dict];
    
    if (![self checkDataTwo:dict]) {
        if ([self.delegate respondsToSelector:@selector(iMateDelegateModuleStatus:)]) {
            
            [self.delegate iMateDelegateModuleStatus:NO];
        }
        [self endTime];
        return NO;
    }
    
    
    if (self.myAction == waitSwipeCardEventAction) {
      
       
        if ([self checkDataTwo:dict]) {
            
            if ([self.delegate respondsToSelector:@selector(iMateDelegateWaitEvent:eventId:data:error:)]) {
                
                NSString *param1 = model.param1;
             
                if (model.arg1 == 1) {
                     [self endTime];
                    NSArray *arr = @[model.data.cardNum == nil?@"":model.data.cardNum,
                                @(model.data.cardType),
                                     model.data.track2 == nil?@"":model.data.track2,
                                     model.data.track3 == nil?@"":model.data.track3];
                    param1 = [arr componentsJoinedByString:@"|"];
                     [self.delegate iMateDelegateWaitEvent:model.resultCode eventId:model.arg1 data:[param1 dataUsingEncoding:NSUTF8StringEncoding] error:model.resultMsg];
                    return NO;
                } else {
                    self.slot = model.arg1;
                    self.param1 = model.param1;
                    [self startPBOCProcess:model.arg1];
                }
            }
            
        }
       
         return NO;
    }
    
    if (self.isCheckIC == YES && (self.slot == 2 || self.slot == 4)) {
        
        self.isCheckIC = NO;
        self.dataModel = [VPODataModel modelWithDict:dict];
        
        if ([self checkDataTwo:dict]) {
            if (self.dataModel.resultCode != 0) {
                
                               if ([self.delegate respondsToSelector:@selector(iMateDelegateICCardInfo:information:error:)]) {
                    
                    [self.delegate iMateDelegateICCardInfo:self.dataModel.resultCode information:nil error:self.dataModel.resultMsg];
                    [self endTime];
                    
                }
                    return NO;
            }
          
            
        }
        [self startPBOCProcess:self.slot];
        return NO;
    }
    
    
    if ([self checkDataTwo:dict]) {
        
        if (model.resultCode != 0) {
            
            if (self.slot == 2 || self.slot == 4) {
                
                [self.delegate iMateDelegateICCardInfo:model.resultCode information:nil error:model.resultMsg];
                [self endTime];
                
                return NO;
            }
            
            
            if ([self.delegate respondsToSelector:@selector(iMateDelegateSwipeCard:track2:track3:error:)]) {
                [self.delegate iMateDelegateSwipeCard:model.resultCode track2:nil track3:nil error:model.resultMsg];
                [self endTime];
            }
            
            return NO;
        }
        self.slot = model.arg1;
        
        return YES;
    } else {
    
        return NO;
    }
    return NO;
}






#pragma mark - set & get

- (NSArray *)supportedProtocolsStrings {
    
    if (!_supportedProtocolsStrings) {
        
        NSBundle *mainBundle = [NSBundle mainBundle];
        _supportedProtocolsStrings = [mainBundle objectForInfoDictionaryKey:@"UISupportedExternalAccessoryProtocols"];
        
    }
    return _supportedProtocolsStrings;
}


- (EAAccessory *)selectedAccessory {
    
    if (self.accessoryList.count == 0) {
        
        return nil;
    }
    
    return self.accessoryList[0];
}

- (NSMutableArray<EAAccessory *> *)accessoryList {
    
    if (_accessoryList == nil) {
        
        NSMutableArray<EAAccessory *> *mtbArr = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];
        _accessoryList = [NSMutableArray new];
        
        for (EAAccessory *ssory in mtbArr) {
            
            if (ssory.protocolStrings.count > 0) {
                
                BOOL isTure = [ssory.protocolStrings[0] isEqualToString:@"com.issc.datapath"];
                if (isTure == YES) {
                    
                    isTure = [ssory.name containsString:@"Chatboard"];
                }
                if (isTure) {
                    
                    [_accessoryList addObject:ssory];
                    _isConnect = [self openSession];
                    
                }
                
            }
            
//            NSLog(@"%@",ssory.protocolStrings[0]);
        }
        
    }
    return _accessoryList;
}

- (NSMutableData *)receverData {
    
    if (!_receverData) {
        
        _receverData = [NSMutableData new];
    }
    return _receverData;
}

- (BOOL)isConnected {
    
    return _isConnect;
}

- (BOOL)reConnect {
    
    return [self openSession];
}

@end
